# -*- coding: utf-8 -*-
import datetime
import math
import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time, urljoin, json, urlencode
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class JiangsuNantongPolicy(BaseTaxPolicySpider):
    name = 'jiangsu_nantong_czj_policy'

    province = '江苏省'
    city = '南通市'
    # county = ''
    park = ''

    def __init__(self, get_next=False, **kwargs):
        super().__init__(**kwargs)
        print(get_next)
        self.get_next = get_next

    @classmethod
    def update_settings(cls, settings) -> None:
        downloader_middlewares = settings.getdict("DOWNLOADER_MIDDLEWARES")
        new_settings = {
            **(cls.custom_settings or {}),
            **{
                # "COOKIES_ENABLED": False,
                "DOWNLOAD_TIMEOUT": 200,
                # "CONCURRENT_REQUESTS": 2,
                "HTTPERROR_ALLOWED_CODES": [302, 400, 404, 500, 200, 202, 502, 429, 521],
                # "DOWNLOAD_DELAY": 5,
                "DOWNLOADER_MIDDLEWARES": {
                    "components.middlewares.downloadmiddlewares.public.jsl_middlewares.JslMiddleware": 543,
                    **downloader_middlewares
                }
            },
        }
        settings.setdict(new_settings or {}, priority="spider")

    def start_requests(self):
        for source, county, url, path in [
            ['南通市财政局', "", "https://czj.nantong.gov.cn/ntsczj/gfxwj/gfxwj.html", "首页>法定主动-公开内容>规章及规范性文件>行政规范性文件"],

        ]:
            item = {'source': source, 'county': county}
            callback = self.parse_url
            yield scrapy.Request(url, callback=callback, meta={'item': item}, dont_filter=True)

    def parse_url(self, response, **kwargs):
        meta = response.meta
        # url = response.xpath("//a[text()='" + meta['path'] + "']/@href").get()
        url = response.xpath(".").re_first(r'url:\s*"(.*?)",')
        lmxx = response.xpath(".").re_first(r"'lmxx':\s*'(.*?)',")
        lmid = response.xpath(".").re_first(r"'lmid':\s*'(.*?)',")
        print(url, lmxx, lmid)
        # siteId = response.xpath(".").re_first("'siteId':(\d+),")
        # channelId = ",".join([response.xpath(".").re_first('var\s*id\s*=\s*"(\d+)";?')] + response.xpath(".").re('id\s*\+\s*","\s*\+\s*(\d+);'))
        # print(channelId)
        formdata = {
            'lmxx': lmxx,
            'lmid': lmid,
            'isGetChild': '1',
            'pagenum': '1',  # 初始页码
            'pagesize': '15',
            'cms_like_document_number': '',
            'cms_in_effectiveness': '',
            'cms_like_msg_title': ''
        }
        meta['formdata'] = formdata
        yield scrapy.FormRequest(
            url=response.urljoin(url),
            method='POST',
            formdata=formdata,
            callback=self.parse_list,
            meta=meta,
        )

    def parse_list(self, response, **kwargs):
        meta = response.meta
        prev_item = meta.get('item')
        # formdata = meta['formdata']
        elem_list = response.json()['msgList']
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem['htmlpath']
            item['source_url'] = response.urljoin(item['source_url'])
            date = elem['fbrq']
            item['publish_date'] = f"{date['year']+1900}-{date['month']+1}-{date['date']:02}"
            item['title'] = elem['msgtitle']
            if item['publish_date'] < '2022-01-01':
                # self.get_next = None
                pass
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if (self.get_next or self.get_next == '0') and meta.get('is_next') is not False:
            total_count = int(response.json()['totalCount'] or 0)
            total_page = math.ceil(total_count / 15)
            print('total', total_page, )
            formdata = meta['formdata']
            for page_num in range(2, total_page + 1):
                formdata['pagenum'] = str(page_num)
                meta.update({'item': prev_item, 'is_next': False})
                # print(params)
                yield scrapy.FormRequest(
                    url=response.url,
                    method='POST',
                    formdata=formdata,
                    meta=meta,
                    callback=self.parse_list,
                )

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        # item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        # item['publish_date'] = response.xpath(
        #     """string(//meta[@name='PubDate']/@content)""").get() or response.xpath(
        #     "//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl jiangsu_nantong_czj_policy -a get_next=0".split())
